'use strict';

let $ = jQuery = window.jQuery = window.$ = require('jquery');
let isProduction = process.env == "production" ? true : false;
const host = 'api.teacher114.cn/api/kcx/v1/user';
const validMethods = ['GET', 'POST'];

function handleParams(api, data, rawMethod, dataType) {
    let method = rawMethod;
    let newUrl = 'http://' + host + api;

    if (rawMethod && validMethods.indexOf(rawMethod) === -1) {
        method = 'POST';
        data._method = rawMethod;
    }

    if (rawMethod === 'GET') {
        // 处理data为空时，不需要拼接&到url上
        let queryStr = $.param(data);
        if (queryStr) {
            if (newUrl.indexOf('?') !== -1) {
                newUrl += '&' + queryStr;
            } else {
                newUrl += '?' + queryStr;
            }
        }

        data = {};
    }

    return Promise.resolve({
        url: newUrl,
        method,
        data,
        dataType
    });
}

/**
 * 模块出口，封装http请求方法
 *
 * @param {string} api 请求接口地址
 * @param {object} data 请求参数
 * @param {string} method 请求方法，默认为GET
 */
function fetch(api, data = {}, rawMethod = 'GET', dataType = 'json') {
    return handleParams(api, data, rawMethod, dataType).then(options => {
        return new Promise((resolve, reject) => {
            $.ajax({
                // headers: {
                //     "Content-Type": "application/json"
                // },
                contentType: "application/json",
                url: options.url,
                method: options.method,
                data: JSON.stringify(options.data),
                dataType: options.dataType,
                jsonpCallback: 'callback',
                timeout: 20000
            }).done((resp) => {
                if (typeof resp.code === 'undefined') {
                    resolve(resp);
                } else if (resp.code === 200) {
                    resolve(resp.data);
                } else {
                    // 把http状态码是200，但是resp.code不是200的请求url打印出来
                    console.error('fetch [%s] fail:', options.url);
                    reject(resp);
                }
            })
            .fail((resp) => reject(resp));
        });
    });
}

export default fetch;
